package com.cloud.common.context;

import com.cloud.common.bean.SessionInfo;
import com.cloud.common.support.SessionCache;
import org.apache.commons.lang3.StringUtils;

/**
 * 会话上下文
 *
 * @author fengwenjin
 */
public class SessionContext {
    public static final String TOKEN = "token";
    public static final String SESSION_INFO = "SessionInfo";

    private static final ThreadLocal<SessionInfo> holder = new ThreadLocal();

    public static void set(SessionInfo sessionInfo) {
        holder.set(sessionInfo);
    }

    public static SessionInfo get() {
        SessionInfo sessionInfo = holder.get();
        if (sessionInfo != null && StringUtils.isEmpty(sessionInfo.getSecret())) {
            // 读取完整会话数据
            SessionCache sessionCache = AppContext.getBean(SessionCache.class);
            sessionInfo = sessionCache.get(sessionInfo.getAppName(), sessionInfo.getUserId());
            set(sessionInfo);
        }
        return sessionInfo;
    }

    public static Long getUserId() {
        SessionInfo sessionInfo = holder.get();
        return sessionInfo != null ? sessionInfo.userId() : 0;
    }

    public static String getAppName() {
        SessionInfo sessionInfo = holder.get();
        return sessionInfo != null ? sessionInfo.getAppName() : "";
    }

    public static void remove() {
        holder.remove();
    }
}
